import { ProTable } from "@ant-design/pro-table";

// 2. 导入“类型”：ActionType 和 ProColumns
import type { ActionType, ProColumns } from "@ant-design/pro-table";

import { Tag,Button } from 'antd';
import {useRef} from "react";
interface User {
  id: number;
  name: string;
  age: number;
  email: string;
  status: 'active' | 'inactive' | 'pending';
  createdAt: string;
}

const mockUsers: User[] = Array.from({ length: 55 }).map((_, i) => ({
  id: i + 1,
  name: `用户 ${i + 1}`,
  age: Math.floor(Math.random() * 40) + 20, // 20-59 岁
  email: `user${i + 1}@example.com`,
  status: ['active', 'inactive', 'pending'][i % 3] as User['status'],
  createdAt: new Date(Date.now() - Math.random() * 1000 * 60 * 60 * 24 * 30).toISOString(), // 过去30天内的随机时间
}));
const mockApiRequest = async (
  params: {
    pageSize?: number;
    current?: number;
    // 下面是我们在 columns 中定义的查询字段
    name?: string;
    status?: string;
  },
  // sort,
  // filter,
): Promise<{ data: User[]; total: number; success: boolean }> => {
  console.log('ProTable 请求参数:', params);

  // 模拟网络延迟
  await new Promise(resolve => setTimeout(resolve, 500));

  let filteredUsers = [...mockUsers];

  // --- 模拟搜索 ---
  if (params.name) {
    filteredUsers = filteredUsers.filter(user => user.name.includes(params.name || ''));
  }
  if (params.status) {
    filteredUsers = filteredUsers.filter(user => user.status === params.status);
  }

  const total = filteredUsers.length;

  // --- 模拟分页 ---
  const { current = 1, pageSize = 10 } = params;
  const startIndex = (current - 1) * pageSize;
  const paginatedUsers = filteredUsers.slice(startIndex, startIndex + pageSize);

  // ProTable 要求返回一个 Promise，其结果为一个包含 data, total, success 的对象
  return {
    data: paginatedUsers,
    total: total,
    success: true,
  };
};

// 4. 定义 ProTable 的列
const columns: ProColumns<User>[] = [
  {
    title: 'ID',
    dataIndex: 'id',
    // 在查询表单中不显示此项
    search: false,
    sorter: (a, b) => a.id - b.id,
  },
  {
    title: '用户名',
    dataIndex: 'name',
    // 默认就会在查询表单中生成一个文本输入框
    // copyable: true, // 可选：开启一键复制
  },
  {
    title: '状态',
    dataIndex: 'status',
    // 在查询表单中，我们希望它是一个下拉选择框
    valueType: 'select',
    valueEnum: {
      active: { text: '活跃', status: 'Success' },
      inactive: { text: '禁用', status: 'Error' },
      pending: { text: '待处理', status: 'Processing' },
    },
    // 在表格中，我们希望它渲染成一个带颜色的 Tag
    render: (_, record) => {
      const statusConfig = {
        active: <Tag color="success">活跃</Tag>,
        inactive: <Tag color="error">禁用</Tag>,
        pending: <Tag color="processing">待处理</Tag>
      };
      return statusConfig[record.status];
    }
  },
  {
    title: '年龄',
    dataIndex: 'age',
    search: false,
    sorter: (a, b) => a.age - b.age,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    search: false,
    copyable: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
    valueType: 'dateTime',
    search: false,
    sorter: (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(),
  },
];


function BasicList() {
  const actionRef = useRef<ActionType>();
  return (
    <ProTable<User>
      headerTitle="用户列表"
      columns={columns}
      // 关键！将我们的模拟请求函数传给 ProTable
      request={mockApiRequest}
      // 表格行的 key，一般是唯一 id
      rowKey="id"
      // 分页器配置
      pagination={{
        // 默认每页数量
        defaultPageSize: 10,
        // 显示快速跳转
        showQuickJumper: true,
      }}
      // 查询表单的配置
      search={{
        // 配置查询按钮和重置按钮的文本
        searchText: '查询',
        resetText: '重置',
        // 默认收起所有查询项
        collapsed: true,
      }}
      // 工具栏渲染
      toolBarRender={() => [
        // 这里可以放 "新建" 等按钮
        <Button key="create" type="primary">新建用户</Button>,
      ]}
      actionRef={actionRef}
    />
  );
}

export default BasicList;
